using UnityEngine;

[DisallowMultipleComponent]
[RequireComponent(typeof(RectTransform))]
public class RandomMove : MonoBehaviour
{
    // 外部从 TestQuad 里赋值（你那四行）
    public float minPos_x;
    public float maxPos_x;
    public float minPos_y;
    public float maxPos_y;

    [Header("速度范围（像素/秒）")]
    public Vector2 speedRange = new Vector2(60f, 120f);

    [Header("随机换向间隔（秒）")]
    public Vector2 changeDirInterval = new Vector2(0.6f, 2.0f);

    [Header("触边策略")]
    public EdgeMode edgeMode = EdgeMode.Bounce;

    [Header("边缘留白（考虑图片尺寸，避免截断）")]
    public float edgePadding = 0f;

    private RectTransform rt;
    private Vector2 dir;     // 归一化方向
    private float speed;     // 当前速度
    private float nextChangeTime;

    public enum EdgeMode
    {
        Bounce, // 反弹
        Wrap,   // 从另一侧出现（打洞/传送门）
        Clamp   // 夹紧到边界，不再越界
    }

    void Awake()
    {
        rt = GetComponent<RectTransform>();
        if (dir == Vector2.zero) dir = Random.insideUnitCircle.normalized;
        speed = Random.Range(speedRange.x, speedRange.y);
        ScheduleNextChange();
    }

    void OnEnable()
    {
        ScheduleNextChange();
    }

    void Update()
    {
        // 以锚点为中心的局部坐标移动（配合 anchor=Middle Center 最稳）
        Vector2 pos = rt.anchoredPosition;

        // 计算考虑图片尺寸与留白后的有效边界
        Vector2 halfSize = rt.rect.size * 0.5f;
        float padX = halfSize.x + edgePadding;
        float padY = halfSize.y + edgePadding;

        float minX = minPos_x + padX;
        float maxX = maxPos_x - padX;
        float minY = minPos_y + padY;
        float maxY = maxPos_y - padY;

        // 移动
        pos += dir * speed * Time.deltaTime;

        bool touchedEdge = false;

        // X 轴边界处理
        if (pos.x < minX || pos.x > maxX)
        {
            touchedEdge = true;
            switch (edgeMode)
            {
                case EdgeMode.Bounce:
                    pos.x = Mathf.Clamp(pos.x, minX, maxX);
                    dir.x = -dir.x; // 反弹
                    break;
                case EdgeMode.Wrap:
                    if (pos.x < minX) pos.x = maxX;
                    else if (pos.x > maxX) pos.x = minX;
                    break;
                case EdgeMode.Clamp:
                    pos.x = Mathf.Clamp(pos.x, minX, maxX);
                    break;
            }
        }

        // Y 轴边界处理
        if (pos.y < minY || pos.y > maxY)
        {
            touchedEdge = true;
            switch (edgeMode)
            {
                case EdgeMode.Bounce:
                    pos.y = Mathf.Clamp(pos.y, minY, maxY);
                    dir.y = -dir.y; // 反弹
                    break;
                case EdgeMode.Wrap:
                    if (pos.y < minY) pos.y = maxY;
                    else if (pos.y > maxY) pos.y = minY;
                    break;
                case EdgeMode.Clamp:
                    pos.y = Mathf.Clamp(pos.y, minY, maxY);
                    break;
            }
        }

        rt.anchoredPosition = pos;

        // 随机换向与变速
        if (Time.time >= nextChangeTime || touchedEdge)
        {
            dir = Random.insideUnitCircle.normalized;
            speed = Random.Range(speedRange.x, speedRange.y);
            ScheduleNextChange();
        }
    }

    private void ScheduleNextChange()
    {
        float t = Random.Range(changeDirInterval.x, changeDirInterval.y);
        nextChangeTime = Time.time + t;
    }

#if UNITY_EDITOR
    void OnDrawGizmosSelected()
    {
        // 在父节点坐标系里画出移动边界（仅编辑器可视化）
        if (!transform.parent) return;
        Gizmos.matrix = transform.parent.localToWorldMatrix;
        Vector3 bl = new Vector3(minPos_x, minPos_y, 0);
        Vector3 br = new Vector3(maxPos_x, minPos_y, 0);
        Vector3 tr = new Vector3(maxPos_x, maxPos_y, 0);
        Vector3 tl = new Vector3(minPos_x, maxPos_y, 0);
        Gizmos.color = Color.cyan;
        Gizmos.DrawLine(bl, br);
        Gizmos.DrawLine(br, tr);
        Gizmos.DrawLine(tr, tl);
        Gizmos.DrawLine(tl, bl);
    }
#endif
}
